package com.bmft.signIn.socketAPI;

import com.bmft.signIn.conf.YamlBeanConf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

@Component
public class PythonScriptTest_01 {
    @Autowired
    YamlBeanConf yamlBeanConf;

    public  String callpython(String dist) {

        Socket socket = null;
        StringBuilder sb = null;
        try {
            InetAddress addr = InetAddress.getLocalHost();
            String host = addr.getHostName();
            //String ip=addr.getHostAddress().toString(); //获取本机ip
            //log.info("调用远程接口:host=>"+ip+",port=>"+12345);

            // 初始化套接字，设置访问服务的主机和进程端口号，HOST是访问python进程的主机名称，可以是IP地址或者域名，PORT是python进程绑定的端口号
            socket = new Socket(yamlBeanConf.getPythonHost(), yamlBeanConf.getPythonPort());

            // 获取输出流对象
            OutputStream os = socket.getOutputStream();
            //输出 流 和编码 设置
            PrintStream out = new PrintStream(os,true,"utf-8");

            out.print(dist);
            // 告诉服务进程，内容发送完毕，可以开始处理
            out.print("over");

            // 获取服务进程的输入流
            InputStream is = socket.getInputStream();
            // 这里设置 输入字符集
            BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
            String tmp = null;
            sb = new StringBuilder();
            // 读取内容
            while ((tmp = br.readLine()) != null)
                sb.append(tmp).append('\n');
//            System.out.print("接受到的数据是:" + sb);
            // 解析结果
            //JSONArray res = JSON.parseArray(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null) socket.close();
            } catch (IOException e) {
            }
            System.out.print("[远程调用接口结束]返回值=");
        }
        return sb.toString();
    }
}
